package com.example.springboot09121.recruitment.service;

import com.example.springboot09121.recruitment.model.User;
import com.example.springboot09121.recruitment.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;


    public void register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

    public Optional<User> login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        Optional<User> res_user = userRepository.findByUsername(username);
        if (res_user.isPresent() && passwordEncoder.matches(password, res_user.get().getPassword())) {
            return res_user;
        }
        return Optional.empty();
    }
}
